/**
 * 获取页面传来的参数
 * @returns {Object}
 */
function parseUrl(){
    var url=location.href;
    var i=url.indexOf('?');
    if(i==-1)return;
    var querystr=url.substr(i+1);
    var arr1=querystr.split('&');
    var arr2=new Object();
    for  (i in arr1){
        var ta=arr1[i].split('=');
        arr2[ta[0]]=ta[1];
    }
    return arr2;
}

/**
 * 身份鉴别成功响应函数
 * @param data 返回数据
 * @param textStatus 请求状态
 * @param request 请求对象
 */
function router(data, textStatus, request) {

    //请求成功，返回成功信息并设置token为cookie
    if (data.meta.state == "success") {

        var btn=$('#submit');
        btn.attr("disabled","false");
        //window.alert(data.meta.message);
        var parent=window.opener;
        var operation=parent.getOperation();

        if(operation==0) {
            parent.addSecUser();
        }
        else if(operation==1){
            var v = parseUrl();//解析所有参数
            //window.alert("operation:"+v['id']+"  "+v['username']);
            //parent.delSecUser(v['id'],v['username']);
            var res=confirm("确认注销用户:"+v['username']+"吗？");
            var id=v['id'];
            if(res){
                $("#del"+id.substr(id.length-6)).attr("disabled","disabled");
                $.ajax({
                    url:HOST.concat("/removesecuser?token="+parent.config.token+"&username="+getSessionStorage("username")),
                    type:"POST",
                    dataType:"json",
                    async:false,
                    data:{
                        "id":id
                    },
                    success:function (data) {
                        $("#del"+id.substr(id.length-6)).removeAttr("disabled");
                        if(data.meta.state=="success"){
                            alert("用户注销成功");
                            parent.userManagement();
                            window.close();
                        }
                    },
                    error:function () {
                        alert("用户注销失败");
                    }
                });
            }else{
                return ;
            }
        }
        else if(operation==2){
            var v = parseUrl();//解析所有参数
            //window.alert("operation:"+v['id']+"  "+v['username']);
            parent.editSecUser(v['id']);
        }
        window.close();
        //location.href=loc+"?token="+config.token;
    }
    //请求失败，返回失败信息并填入提示栏
    else {
        var btn=$('#submit');
        btn.attr("disabled","false");
        var flag=data.meta.message;
        if (flag==0||flag=="0"){
            window.alert("校验失败，请重新输入");
        } else {
            window.alert("失败次数过多，已锁定");
            window.close();
            var parent=window.opener;
            parent.window.location.href= "login.html";
        }
        location.reload();
        createCode();
    }
}

/**
 * 发出登录请求
 * @param data 表单数据
 * @param callback 成功回调函数
 */
function logIn(data, callback) {
    $.ajax({
        type: "POST",
        url: HOST.concat("/login"),
        contentType: "application/x-www-form-urlencoded",
        data: data,
        dataType: "JSON",
        success: callback,
        error: function () {
            console.error("error!");
        }
    });
}

/**
 * 登录表单提交动作
 */
function submit() {
    //锁定按钮，防止重复提交
    var btn=$('#submit');
    btn.attr("disabled","true");
    //获取用户名密码
    var username = getSessionStorage("username");
    var password = $("#password");
    //获取提示信息
    var warntext = $('.warn-text');
    warntext.text("");
    // if (username.val() == "") {
    //     username.val("");
    //     warntext.text("用户名不能为空");
    //     return;
    // }
    if (password.val() == "") {
        password.val("");
        warntext.text("密码不能为空");
        return;
    }
    if ('right'!=validate()){
        return;
    }

    var data = {
        username: username,
        password: encrypt(md5(password.val()+'scuwsn')),
        timeline: new Date().getTime(),
        flag:false
    };
    // var data = {
    //      username: username.val(),
    //      password: password.val(),
    //  };

    logIn(data, router);
}

/**
* 加密（需要先加载lib/aes/aes.min.js文件）
* @param word
* @returns {*}
*/
function encrypt(word) {
    var jsEncrypt = new JSEncrypt();
    var key = sessionStorage.getItem("publicKey");
    jsEncrypt.setPublicKey(key);
    var encrypted = jsEncrypt.encrypt(word);
    return encrypted.toString();
}

/**
 * 解密
 * @param word
 * @returns {*}
 */
function decrypt(word,key) {
    var key = CryptoJS.enc.Utf8.parse(key);
    var decrypt = CryptoJS.AES.decrypt(word, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}



function keyLogin(){
    if (event.keyCode==13){
        submit();
    }
}
function clearWarn() {
    var warntext = $('.warn-text');
    warntext.text("");
}

$("#submit").click(function () {
    submit();
});

$('#submit').blur(function () {
    clearWarn();
});
$('body').keydown(function (event) {
    keyLogin();
});

//设置一个全局的变量，便于保存验证码
var code;
function createCode(){
    //首先默认code为空字符串
    code = '';
    //设置长度，这里看需求，我这里设置了4
    var codeV = document.getElementById('code');
    //设置随机字符
    $.ajax({
        url: HOST.concat("/IDCode"),
        type: "GET",
        success: function(datas){
            code = datas.data.IDCode;
            drawPic(code);
        },
        error: function(){
            console.log("请求验证码错误！");
        },
        dataType: "json",
    });

}

//下面就是判断是否== 的代码，无需解释
function validate(){
    var warntext = $('.warn-text');
    warntext.text("");
    var result = "";
    var oValue = document.getElementById('codeInput').value.toUpperCase();
    var btn=$('#submit');
    btn.attr("disabled","false");
    if(oValue ==''||oValue==undefined){
        warntext.text('请输入验证码');
        return;
    }else {
        $.ajax({
            url: HOST.concat("/checkIDCode?code="+oValue),
            type: "GET",
            async: false,
            success: function (datas) {
                result = datas.meta.state;
            },
            error: function(){
                console.log("请求验证码错误！");
            },
            dataType: "json",
        });
        if(result=='success'){
            return 'right';
        }else {
            warntext.text('验证码不正确，请重新输入');
            btn.removeAttr("disabled");
            createCode();
            //location.reload();
            return;
        }
    }
}


/**生成一个随机数**/
function randomNum(min,max){
    return Math.floor( Math.random()*(max-min)+min);
}
/**生成一个随机色**/
function randomColor(min,max){
    var r = randomNum(min,max);
    var g = randomNum(min,max);
    var b = randomNum(min,max);
    return "rgb("+r+","+g+","+b+")";
}


/**绘制验证码图片**/
function drawPic(IDCode){
    var canvas=document.getElementById("canvas");
    var width=canvas.width;
    var height=canvas.height;
    var ctx = canvas.getContext('2d');
    ctx.textBaseline = 'bottom';

    /**绘制背景色**/
    ctx.fillStyle = randomColor(180,240); //颜色若太深可能导致看不清
    ctx.fillRect(0,0,width,height);
    /**绘制文字**/

    /*   for(var i=0; i<4; i++){ */
    var txt = IDCode;
    ctx.fillStyle = randomColor(50,160);  //随机生成字体颜色
    ctx.font = randomNum(25,30)+'px SimHei'; //随机生成字体大小
    var x = randomNum(15,20);
    var y = randomNum(30,35);
    //修改坐标原点和旋转角度
    ctx.translate(x,y);
    ctx.fillText(txt, 0,0);
    //恢复坐标原点和旋转角度
    ctx.translate(-x,-y);
    /*    } */
    /* /**绘制干扰线**/
    for(var i=0; i<8; i++){
        ctx.strokeStyle = randomColor(40,180);
        ctx.beginPath();
        ctx.moveTo( randomNum(0,width), randomNum(0,height) );
        ctx.lineTo( randomNum(0,width), randomNum(0,height) );
        ctx.stroke();
    }
    /**绘制干扰点**/
    /*  for(var i=0; i<100; i++){
     ctx.fillStyle = randomColor(0,255);
     ctx.beginPath();
     ctx.arc(randomNum(0,width),randomNum(0,height), 1, 0, 2*Math.PI);
     ctx.fill();
     }  */
}

//设置此处的原因是每次进入界面展示一个随机的验证码，不设置则为空
window.onload = function (){
    createCode();
};